<?php
/**
 * OAuth2 Service
 * User: zng
 * Date: 2020/3/19
 * Time: 16:20
 */
namespace app\api\service\user;

use app\api\model\user\Address as AddressModels;
use think\Db;

Class Address {

    /**
     * 收货地址列表
     *
     * @return mixed
     */
    public function index()
    {
        return AddressModels::order('id','desc')->selectOrFail();
    }

    /**
     * 添加收货地址
     * @param AddressModels $model
     * @param array $post
     * @return bool|int
     */
    public function create(array $post)
    {
        Db::startTrans();
        if ( $post['default'] == 1 ) {
            if ( false === $this->cleanDefault() ) {
                Db::rollback();
                return false;
            }
        }
        $address = AddressModels::create($post, ['username','mobile','area','address','default']);
        if ( false === $address->isEmpty() ) {
            Db::commit();
            return $address->id;
        }
        Db::rollback();
        return false;
    }

    /**
     * 清除其他默认信息
     * @return bool
     */
    private function cleanDefault()
    {
        $addressModels = AddressModels::where('default', 1)->findOrEmpty();
        if ( $addressModels->isEmpty() ) {
            return true;
        }
        $addressModels->default = 0;
        return $addressModels->save();
    }

    /**
     * 编辑收货地址
     * @
     * @return bool
     */
    public function save(AddressModels $model, array $data)
    {
        Db::startTrans();
        if ( $data['default'] == 1 ) {
            if ( false === $this->cleanDefault() ) {
                Db::rollback();
                return false;
            }
        }
        $model->default = $data['default'];
        $model->username = $data['username'];
        $model->mobile = $data['mobile'];
        $model->area = $data['area'];
        $model->address = $data['address'];
        if ( false === $model->save() ) {
            Db::rollback();
            return false;
        }
        Db::commit();
        return true;
    }

    /**
     * 删除
     * @param int|array $data
     * @return bool
     */
    public function destory($data)
    {
        return AddressModels::destroy(function($query)use($data){
            $where = ['id', '=', $data];
            if ( is_array($data) ) {
                $where = ['id', 'in', $data];
            }
            $query->where([
                $where
            ]);
        });
    }

    /**
     * 获取指定地址或默认地址
     *
     * @return mixed
     */
    public function defaultAddress(int $id)
    {
        if ( $id > 0 ) {
            return AddressModels::where('id', $id)->findOrFail();
        }
        return AddressModels::where('default', 1)->findOrFail();
    }

    /**
     * 获取收货地址详情
     * @param int $id
     * @return mixed
     */
    public function read(int $id)
    {
        return AddressModels::field('area,username,mobile,address')->get($id);
    }

}